﻿using B.S.BasicData.Api.Read.Applications.Command;
using B.S.BasicData.Api.Read.Dto;
using B.S.BasicData.Domains;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructures;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace B.S.BasicData.Api.Read.Applications.CommandHandler
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, ApiResult<UserDto>>
    {
        private readonly IBaseRepository<UserInfos> baseRepository;
        private readonly IBaseRepository<Role> roleRepository;
        private readonly IBaseRepository<RoleUser> userRoleRepository;
        private readonly IBaseRepository<Permissons> PermissonRepository;
        private readonly IBaseRepository<RolePermissons> RolePermissonRepsoitory;
        public LoginCommandHandler(IBaseRepository<UserInfos> baseRepository, IBaseRepository<Role> roleRepository, IBaseRepository<RoleUser> userRoleRepository, IBaseRepository<Permissons> permissonRepository, IBaseRepository<RolePermissons> rolePermissonRepsoitory)
        {
            this.baseRepository = baseRepository;
            this.roleRepository = roleRepository;
            this.userRoleRepository = userRoleRepository;
            PermissonRepository = permissonRepository;
            RolePermissonRepsoitory = rolePermissonRepsoitory;
        }


        public Task<ApiResult<UserDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            ApiResult<UserDto> result = new ApiResult<UserDto>();
            result.Code = ApiEnum.Success;
            result.Message = "登录成功";

            var a1 = request.Password.GetMD5();
            var list = from a in baseRepository.GetAll()
                       join b in userRoleRepository.GetAll() on a.UserId equals b.UserId
                       join c in roleRepository.GetAll() on b.RoleId equals c.RoleId
                       join d in RolePermissonRepsoitory.GetAll() on c.RoleId equals d.RoleId   
                       join e in PermissonRepository.GetAll() on d.PermissonId equals e.PermissonId
                       where (a.UserName == request.UserName)
                       select new UserDto
                       {
                           UserId = a.UserId,
                           UserName = a.UserName,
                           NickName = a.NickName,
                           Password = a.Password,
                           RoleName = c.RoleName,
                           RoleId = c.RoleId,
                           //PermissonId=d.PermissonId,
                           PermissonName=e.PermissonName,
                           PermissonValue=e.PermissonValue,
                           


                       };
           

            var entity = list.FirstOrDefault();
            if(entity==null)
            {
                result.Code = ApiEnum.Fail;
                result.Message = "用户名不存在,请联系管理员"; 
                return Task.FromResult(result);
            }
            if (entity.Password != a1)
            {
                result.Code = ApiEnum.Fail;
                result.Message = "用户密码不匹配";
                return Task.FromResult(result);
            }
            entity.Token = CreateTokenString(entity);
            result.data = entity;
            return Task.FromResult(result);
        }
        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString(UserDto dto)
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            var Claim = new[]
            {
                new Claim("UserId",dto.UserId.ToString()),
                new Claim("UserName",dto.UserName),
                new Claim("Password",dto.Password),
                new Claim("RoleName",dto.RoleName),
                new Claim("NickName",dto.NickName),
            };
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims:Claim
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
